/**
 * 结算方式管理
 */
Ext.namespace('Divo');
Ext.namespace('Divo.app');

Divo.app.ReadyCodeList = function() {
  /* ----------------------- private属性 ----------------------- */
  var gridEl = 'ReadyCode-grid';
  var grid, form, selModel, toolbar, win, win2;
  var data, sId;
  var fldEndTime;
  var d = new Date();
  var year = d.getYear().toString();
  var month = (d.getMonth() + 1).toString();
  var day = d.getDate().toString();
  var time;
  var printHtml;
  var printShowPanel, printShowWin;
  if (month.length > 1) {
    time = year + month;
  } else {
    time = year + "0" + month;
  }

  if (day.length > 1) {
    time = time + day;
  } else {
    time = time + "0" + day;
  }

  /* ----------------------- private方法 ----------------------- */
  // 创建列表
  function createGrid() {
    var queryFlds = new Array();
    var searchFlds = new Ext.util.MixedCollection();
    queryFlds.push('name');
    var fldName = new Ext.form.TextField({
          name : 'name',
          id : gridEl + '-name',
          fieldLabel : '名称',
          allowBlank : true,
          width : 100

        });

    fldEndTime = new app.base.DateField({
          name : "endTime",
          dataIndex : "endTime",
          format : 'Y.m.d',
          fieldLabel : "有效日期",
          allowBlank : false,
          labelSeparator : ":*",
          width : 150,
          editable : true,
          insert_allowed : true,
          update_allowed : true
        });
    searchFlds.add('name', fldName);

    grid = new Divo.Base.GridView({
          remoteSort : true,
          gridId : gridEl,
          queryFlds : queryFlds,
          searchFlds : searchFlds,
          checkboxSelectionModel : true,
          autoSelectFirstRow : false,
          entityClassName : 'com.our.sys.project1.entity.ReadyCode',
          queryUrl : 'ready_code/query',
          deleteUrl : 'ready_code/delete',
          specialFields : ["id", "name", "materialId", "materialName", "spec",
              "consum", "unit", "managerCode", "supplierId", "supplierName",
              "regNo", "readyCodeTime", "readyCodeWho", "readyCodeState",
              "endTime", "state", "cancelCodeTime", "readyCodeNumber",
              "cancelCodeWho"],
          jsonId : 'id',
          recordPk : ["id"]
        });
    selModel = grid.getSelectionModel();
    selModel.on('rowselect', onRowSelect);
    grid.on('rowselect', onRowSelect);

    var cm = grid.getColumnModel();
    for (i = 0; i < cm.getColumnCount(); i++) {
      if (cm.getDataIndex(i) == "readyCodeState") {
        cm.setRenderer(i, function(val, params, record) {
              if (val == "0") {
                return "备码";
              }

              if (val == "1") {
                return "备货";
              }

              if (val == "2") {
                return "取消备货";
              }

              if (val == "3") {
                return "配发";
              }

              if (val == "4") {
                return "已划价";
              }

              if (val == "5") {
                return "已入库";
              }
            });
      }
      if (cm.getDataIndex(i) == "state") {
        cm.setRenderer(i, function(val, params, record) {
              // TODO
              // 时间有效那么就是有效的
              var endTime = record.data.endTime;
              var year = endTime.substring(0, 4);
              var month = endTime.substring(5, 7);
              var day = endTime.substring(8, 10);
              var endTimeStr = year + month + day;
              if (parseInt(endTimeStr) - parseInt(time) >= 0) {
                return "OK";
              } else {
                return "NO";
              }
            });
      }
    }

    printShowPanel = new Ext.Panel({
          border : false,
          height : 400,
          width : 900
        });
  }
  // 选择某行
  function onRowSelect(selModel, rowIndex, record) {
    data = record.data;
    sId = data.id;
  }

  // 刷新列表
  function reloadRecords() {
    grid.getStore().reload();
  }

  function createPrintWin() {
    printShowWin = new Ext.Window({
          title : '打印预览',
          iconCls : 'icon-win',
          autoHeight : true,
          width : 900,
          height : 400,
          layout : 'form',
          plain : false,
          buttonAlign : 'right',
          closable : false,
          modal : true,// /
          items : [printShowPanel]
        });
    var yesBtn = printShowWin.addButton({
          text : '打印'
        }, printThisWin, this);
    var cancelBtn = printShowWin.addButton({
          text : '关闭'
        }, onPrintWinHide, this);

    printShowWin.show();
  }

  function onPrintWinHide() {
    printShowWin.hide();
  }

  // 创建新的记录，初始化表单
  function createNewRecord() {

    form.loadRecord(new form.dataRecordMeta({
          _p_record_status : "insert",
          id : "",
          supplierId : "",
          materialId : "",
          endTime : "",
          supplier : "",
          materialNameG : "",
          materialName : "",
          name : ""
        }));
    win = new Ext.Window({
          title : '新增高值耗材备码',
          iconCls : 'icon-win',
          autoHeight : true,
          width : 320,
          layout : 'form',
          plain : false,
          buttonAlign : 'right',
          closable : false,
          modal : true,
          items : [form]
        });
    var yesBtn = win.addButton({
          text : '确定'
        }, commitForm, this);
    var cancelBtn = win.addButton({
          text : '关闭'
        }, onWinHide, this);

    win.show();
  }
  function onWinHide() {
    win.hide();
  }

  // 创建form表单
  function createForm() {
    form = new Divo.app.ReadyCodeForm({
          layout : 'fit',
          region : 'east',
          border : true,
          split : true,
          width : 320,
          minSize : 300,
          maxSize : 400,
          submitUrl : 'ready_code/save'
        });

    form.on('commitFormSuccess', afterCommitFormSuccess);

  }

  // 新建或修改表单成功提交后,重新加载其父节点
  function afterCommitFormSuccess(operation, recordData) {
    grid.getStore().reload();
  }

  // 创建layout
  function createLayout() {
    toolbar = new Ext.Toolbar({
          items : [{
                xtype : "button",
                cls : "x-btn-icon",
                icon : "resources/img/g_rec_src.png",
                tooltip : "过滤数据",
                id : "tlb_FILTER",
                handler : toggleFilterBar
              }, {
                icon : "resources/img/g_rec_new.png",
                text : "新增",
                id : "tlb_NEW",
                handler : createNewRecord
              }, '-', {
                icon : "resources/img/g_rec_new.png",
                text : "重新编码",
                id : "tlb_EDIT",
                handler : toggleEditMode
              }, '-', {
                icon : "resources/img/g_rec_del.png",
                text : "取消编码",
                id : "tlb_CANCEL",
                handler : cancelCode
              }, '-', {
                icon : "resources/img/g_rec_del.png",
                text : "打印",
                id : "tlb_PRINT",
                handler : printCode
              }, {
                icon : "resources/img/g_rec_refresh.gif",
                text : "刷新",
                id : "tlb_REFRESH",
                handler : reloadRecords
              }]
        });
    var viewport = new Ext.Viewport({
          layout : 'border',
          items : [{
                layout : 'border',
                region : 'center',
                border : false,
                items : [{
                      layout : 'fit',
                      region : 'north',
                      border : false,
                      items : [toolbar],
                      height : 25
                    }, {
                      layout : 'fit',
                      region : 'center',
                      border : false,
                      items : [grid]
                    }]
              }]
        });

    viewport.doLayout();
  }

  // 切换过滤查询工具条状态
  function toggleFilterBar() {
    grid.toggleFilterBar();
  }

  function cancelCode() {
    Ext.Msg.show({
          title : '确认',
          msg : '是否确认?',
          buttons : Ext.Msg.YESNO,
          fn : function(btn) {
            if (btn == 'yes') {
              Ext.Ajax.request({
                    params : {
                      id : sId
                    },
                    url : "ready_code/cancel",
                    callback : function(o, s, r) {
                      var respText = Ext.decode(r.responseText);
                      if (respText.success) {
                        grid.getStore().reload();
                        Ext.Msg.alert('成功', "取消备码成功！");
                      } else {
                        if (respText.message.length > 0)
                          Ext.Msg.alert('错误', respText.message);
                      }
                    }
                  });
            }
          },
          scope : this,
          icon : Ext.MessageBox.QUESTION
        });
  }

  // 切换记录编辑状态
  function toggleEditMode() {
    win2 = new Ext.Window({
          title : '新增高值耗材备码',
          iconCls : 'icon-win',
          autoHeight : true,
          width : 320,
          layout : 'form',
          plain : false,
          buttonAlign : 'right',
          closable : false,
          modal : true,
          items : [fldEndTime]
        });
    var yesBtn = win2.addButton({
          text : '确定'
        }, commitForm2, this);
    var cancelBtn = win2.addButton({
          text : '关闭'
        }, onWinHide2, this);

    win2.show();
  }

  function printCode() {
    // 根据勾选条目查询每个记录对应的条目图片
    var sels = selModel.getSelections();
    var codes = "";
    for (var i = 0; i < sels.length; i++) {
      var sel = sels[i];
      var data = sel.data;
      var managerCode = data.managerCode;
      if ("" == codes) {
        codes = managerCode;
      } else {
        codes = codes + "," + managerCode;
      }
    }

    // 打开一个窗口作为预览
    Ext.Ajax.request({
          params : {
            codes : codes
          },
          url : "ready_code/print_code",
          callback : function(o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success) {
              // 打开一个窗口作为预览
              printHtml = respText.html;
              printShowPanel.html = printHtml;
              createPrintWin();
            } else {
              if (respText.message.length > 0)
                Ext.Msg.alert('错误', respText.message);
            }
          }
        });

    // 点击打印，实行打印
  }

  function printThisWin() {
    var oldStr = window.document.body.innerHTML;
    window.document.body.innerHTML = printHtml;
    window.print();
    window.document.body.innerHTML = oldStr;
  }

  function commitForm2() {
    var endTime = fldEndTime.getValue();
    Ext.Msg.show({
          title : '确认',
          msg : '是否确认?',
          buttons : Ext.Msg.YESNO,
          fn : function(btn) {
            if (btn == 'yes') {
              Ext.Ajax.request({
                    params : {
                      id : sId,
                      endTime : endTime
                    },
                    url : "ready_code/re_ready",
                    callback : function(o, s, r) {
                      var respText = Ext.decode(r.responseText);
                      if (respText.success) {
                        grid.getStore().reload();
                        onWinHide2();
                        Ext.Msg.alert('成功', "重新备码成功！");
                      } else {
                        if (respText.message.length > 0)
                          Ext.Msg.alert('错误', respText.message);
                      }
                    }
                  });
            }
          },
          scope : this,
          icon : Ext.MessageBox.QUESTION
        });
  }
  function onWinHide2() {
    win2.hide();
  }
  // 提交表单，保存新建或修改的信息
  function commitForm() {
    form.commitForm();
    win.hide();
  }

  /* ----------------------- public方法 ----------------------- */
  return {
    /**
     * 初始化
     */
    init : function() {
      createGrid();
      createForm();
      createLayout();
      grid.load();
      // window.print();
    }
  }
}();

Ext.onReady(Divo.app.ReadyCodeList.init, Divo.app.ReadyCodeList, true);